import hashlib

from flask import Flask, request, json
from sqlalchemy import create_engine, Table, Select, or_, func, outerjoin
from sqlalchemy.orm import sessionmaker, declarative_base, scoped_session

app = Flask(__name__)

# 创建引擎，链接数据库
engine = create_engine('mysql+pymysql://root:admin@127.0.0.1:3306/mumu', echo=True)
# 打开数据库的连接会话
session = sessionmaker(engine)
# 保证线程安全
db_session = scoped_session(session)
# 获取基类
Base = declarative_base()


class User(Base):
    # 表结构反射加载
    __table__ = Table("user", Base.metadata, autoload_with=engine)

class Article(Base):
    # 表结构反射加载
    __table__ = Table("article", Base.metadata, autoload_with=engine)

# class Favorite(Base):
#     # 表结构反射加载
#     __table__ = Table("favorite", Base.metadata, autoload_with=engine)

@app.route("/")
def my_article():
    keyword = request.args.get('keyword')
    result = db_session.query(Article).filter(or_(Article.content.like("%" + keyword + "%"),
                                                  Article.title.like("%" + keyword + "%"))).all()
    # print(model_list(result))
    # for article in result:
    #     print(article.title)
    return model_list(result)


def model_list(list):
    list_result = []
    for row in list:
        print(row.__dict__)
        my_dict = {}
        for k,v in row.__dict__.items():
            if not k.startswith('_sa'):
                my_dict[k] = v
        list_result.append(my_dict)
    return list_result


if __name__ == '__main__':
    app.run(debug=True)